package myky.com.doctorapp.presenter

import io.reactivex.disposables.Disposable
import myky.com.doctorapp.base.BasePresenterIm
import myky.com.doctorapp.base.RxPageSubscribe
import myky.com.doctorapp.base.RxSubscribe
import myky.com.doctorapp.contract.FindDoctorContract
import myky.com.doctorapp.entity.DepatmentWrapperEntity
import myky.com.doctorapp.entity.DoctorWrapperEntity
import myky.com.doctorapp.entity.PageEntity
import myky.com.doctorapp.model.FindDoctorModel
import rx.Observable

class FindDoctorPresenter : BasePresenterIm<FindDoctorContract.View>(), FindDoctorContract.Presenter {
    override fun findDoctorList(version: String, customerId: String, size: Int, current: Int, type: String) {
        findDoctorModel.findDoctorList(version, customerId, size, current, type).subscribe(object : RxPageSubscribe<DoctorWrapperEntity.DoctorListEntity>() {
            override fun onSuccess(t: DoctorWrapperEntity.DoctorListEntity, pageEntity: PageEntity) {
                val doctorListResult = t.doctors
                doctorListResult.let { mView.showDoctorList(doctorListResult) }
                mView.showPages(pageEntity)
                mView.hideLoading()
            }

            override fun onFailed(code: Int, msg: String?) {
                mView.showDataError(msg)
            }

            override fun onSubscribe(d: Disposable) {
                mView.showLoadingView()
                addSubscription(d)
            }
        })
    }

    private var findDoctorModel: FindDoctorModel = FindDoctorModel()

    override fun findDepartMent() {

        findDoctorModel.findDepartMent().subscribe(object : RxSubscribe<DepatmentWrapperEntity.Depatment>() {
            override fun onSuccess(t: DepatmentWrapperEntity.Depatment?) {
                val department = t?.department

                val departMents = ArrayList<String>()

                Observable.from(department)
                        .flatMap { t -> Observable.from(t?.departmentchild) }.subscribe { t ->
                            val departmentchildname = t?.departmentchildname
                            departmentchildname?.let { departMents.add(it) }
                        }

                mView.showDepartMentList(departMents)

            }

            override fun onFailed(code: Int, msg: String?) {
                mView.logCat("onFailed")
            }

            override fun onSubscribe(d: Disposable) {
                addSubscription(d)
            }

        })

    }
}
